1
|
|
|
import Relation from "../Relation"; |
2
|
|
|
import {ModelStaticInterface} from "../../../JeloquentInterfaces"; |
3
|
|
|
import Collection from "../../Collection"; |
4
|
|
|
import ForeignKey from "../Field/ForeignKey"; |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* |
8
|
|
|
*/ |
9
|
|
|
export default class HasMany extends Relation { |
10
|
|
|
|
11
|
|
|
localKey: string; |
12
|
|
|
|
13
|
|
|
constructor(model: ModelStaticInterface, foreignKey: string = null, localKey: string = null) { |
14
|
|
|
super(model, foreignKey); |
15
|
|
|
this.localKey = localKey ?? 'id'; |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
get count(): number { |
19
|
|
|
const indexes = globalThis.Store.database().indexes(this.model.className); |
20
|
|
|
return indexes.get(this.foreignKey).get(this.$parent.primaryKey)?.size ?? 0; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
get originalValue(): unknown { |
24
|
|
|
return this.getValueByParentKey('originalPrimaryKey'); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
get value(): unknown { |
28
|
|
|
return this.getValueByParentKey('primaryKey'); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
getRelationalFields():Array<ForeignKey> { |
32
|
|
|
return []; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
setName(): HasMany { |
36
|
|
|
const parentClassName = this.$parent.snakeCaseClassName; |
37
|
|
|
const modelClassName = this.model.snakeCaseClassName; |
38
|
|
|
|
39
|
|
|
this.foreignKey = `${parentClassName}_id`; |
40
|
|
|
this.$name = `${modelClassName}s`; //todo fix plural notation |
41
|
|
|
return this; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
protected getValueByParentKey(parentProperty): Collection { |
45
|
|
|
const keyIndex = this.model.getIndexByKey(this.foreignKey); |
46
|
|
|
return globalThis.Store.database().find(this.model.className, |
47
|
|
|
[...keyIndex.get(`${this.$parent[parentProperty]}`)?.values() ?? []] |
48
|
|
|
); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
protected setParentProperties(): HasMany { |
52
|
|
|
super.setParentProperties(); |
53
|
|
|
|
54
|
|
|
// todo remove and move to proxy |
55
|
|
|
Object.defineProperty(this.$parent, |
56
|
|
|
`${this.name}Count`, { |
57
|
|
|
get: () => { |
58
|
|
|
return this.count; |
59
|
|
|
}, |
60
|
|
|
} |
61
|
|
|
); |
62
|
|
|
|
63
|
|
|
// todo remove and move to proxy |
64
|
|
|
Object.defineProperty(this.$parent, |
65
|
|
|
`has${this.model.className}s`, { |
66
|
|
|
get: () => { |
67
|
|
|
return this.count > 0; |
68
|
|
|
}, |
69
|
|
|
} |
70
|
|
|
); |
71
|
|
|
return this; |
72
|
|
|
} |
73
|
|
|
} |